<template>
  <a-row :class="['p-4', `${prefixCls}--box`]" type="flex" :gutter="10">
    <a-col :xl="defectXl" :lg="24" :md="24" style="margin-bottom: 10px;margin-left: -10px;">
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="12">
          <a-form-item label="项目名称" v-bind="validateInfos.projectId">
	          <j-search-select v-model:value="formData.projectId" dict="tm_project,project_name,id" @change="projectChange" placeholder="请选择项目名称" :disabled="disabled"  allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="批次名称" v-bind="validateInfos.batchId">
	          <j-search-select v-model:value="formData.batchId" dict="tm_project_batch,batch_name,id" placeholder="请选择批次名称" :disabled="disabled"  allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="系统名称" v-bind="validateInfos.systemId">
            <j-search-select ref="refSystem" v-model:value="formData.systemId" :dict="searchProjectSystemString"  placeholder="请选择系统名称" :disabled="disabled"  allowClear/>
	          <!-- <j-search-select ref="refSystem" v-model:value="formData.systemId" dict="tm_project_system,system_name,id" placeholder="请选择系统名称" :disabled="disabled" /> -->
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="模块名称" v-bind="validateInfos.systemModuleId">
	          <j-tree-select
	            dict="tm_system_module,module_name,id"
	            pidValue=""
	            :disabled="disabled"
	            v-model:value="formData.systemModuleId"
	            @change="(value) => handleFormChange('systemModuleId', value)"  allowClear>
	          </j-tree-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="功能点" v-bind="validateInfos.functionName">
            <a-input v-model:value="formData.functionName" placeholder="请输入功能点" :disabled="disabled"  allowClear></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="缺陷等级" v-bind="validateInfos.defectLevel">
	          <j-search-select v-model:value="formData.defectLevel" dict="defect_level" placeholder="请选择缺陷等级" :disabled="disabled"  allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="缺陷类型" v-bind="validateInfos.defectType">
	          <j-search-select v-model:value="formData.defectType" dict="defect_type" placeholder="请选择缺陷类型" :disabled="disabled"  allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="轮次名称" v-bind="validateInfos.testStage">
	          <j-search-select v-model:value="formData.testStage" dict="tm_test_stage where status='Y' order by sort_order asc,test_stage_name,id" placeholder="请选择轮次名称" :disabled="disabled"  allowClear/>
          </a-form-item>
        </a-col>
<!-- 
        <a-col :span="24">
          <div style="margin-left: -105px;">
          <a-form-item label="缺陷描述" v-bind="validateInfos.defectTitle">
            <a-input v-model:value="formData.defectTitle" placeholder="请输入缺陷描述" :disabled="disabled" style="width:655px"></a-input>
          </a-form-item>
        </div>
        </a-col> -->
        <a-col :span="24">
          <a-form-item :span="24" label="缺陷描述" v-bind="validateInfos.defectTitle">
            <a-input v-model:value="formData.defectTitle" placeholder="请输入缺陷描述" :disabled="disabled"  allowClear></a-input>
	          <!-- <a-textarea v-model:value="formData.defectTitle" :rows="4" placeholder="请输入缺陷描述" :disabled="disabled"/> -->
          </a-form-item>
       
        </a-col>
        <a-col :span="24">
          <a-form-item :span="24" label="操作步骤" v-bind="validateInfos.description">
	          <a-textarea v-model:value="formData.description" :rows="4" placeholder="请输入操作步骤" :disabled="disabled"  allowClear/>
          </a-form-item>
        </a-col>
       
        <a-col :span="12">
          <a-form-item label="环境" v-bind="validateInfos.envType">
	          <j-search-select v-model:value="formData.envType" dict="env_type" placeholder="请选择环境" :disabled="disabled"  allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="缺陷优先级" v-bind="validateInfos.defectPriority">
	          <j-search-select v-model:value="formData.defectPriority" dict="defect_priority" placeholder="请选择缺陷优先级" :disabled="disabled"  allowClear/>
          </a-form-item>
        </a-col>
        <!-- 
          已驳回，已挂起，无效缺陷，遗留,遗留关闭是显示不解决原因
          默认新增是为新建
          重复缺陷 添加 关联重复缺陷
        -->
        <a-col :span="12">
          <a-form-item label="缺陷状态" v-bind="validateInfos.bugStatus">
	          <j-search-select v-model:value="formData.bugStatus" dict="bug_status" @change="bugStatusChange" placeholder="请选择缺陷状态" :disabled="disabled"  allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="缺陷处理人" v-bind="validateInfos.solverId">
            <j-search-select ref="refSolverer" v-model:value="formData.solverId" :dict="searchSolvererString" placeholder="请选择缺陷处理人" :disabled="disabled"  allowClear/>
            <!-- <j-search-select v-model:value="formData.solverId" dict="sys_user where status='1',realname,username" placeholder="请选择缺陷处理人" :disabled="disabled"  allowClear/> -->
			  <!-- <j-select-user v-model:value="formData.solverId" :disabled="disabled"/> -->
          </a-form-item>
        </a-col>

        <a-col :span="12" v-if="showFlag">
          <a-form-item label="原因分类" v-bind="validateInfos.defectReasonCata">
	          <j-search-select v-model:value="formData.defectReasonCata" dict="defect_reason_cata" placeholder="请选择原因分类" :disabled="disabled"  allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="showFlag">
          <a-form-item label="是否有影响" v-bind="validateInfos.isInfects">
	          <j-dict-select-tag v-model:value="formData.isInfects" dictCode="yn" @change="isInfectsChange" placeholder="请选择是否有影响" :disabled="disabled"  allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="showFlag">
          <a-form-item :span="24" label="影响范围" v-bind="validateInfos.infects">
	          <a-textarea v-model:value="formData.infects" :rows="4" placeholder="请输入影响范围" :disabled="disabled" style="height:55px"  allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="showFlag">
          <a-form-item :span="24" label="缺陷原因" v-bind="validateInfos.defectReason">
	          <a-textarea v-model:value="formData.defectReason" :rows="4" placeholder="请输入缺陷原因" :disabled="disabled" style="height:55px"  allowClear/>
          </a-form-item>
        </a-col >
        <a-col :span="24" v-if="showFlag">
          <a-form-item :span="24" label="不解决原因" v-bind="validateInfos.noSloveReason">
	          <a-textarea v-model:value="formData.noSloveReason" :rows="4" placeholder="请输入不解决原因" :disabled="disabled" style="height:55px"  allowClear/>
          </a-form-item>
        </a-col>

        <a-col :span="24" v-if="showFlag">
          <a-form-item :span="24" label="重复缺陷" v-bind="validateInfos.repeatDefectId">
            <!-- <j-search-select v-model:value="formData.defectId" dict="tm_defect_manage,id,defect_title" :disabled="disabled" /> -->
            <j-search-select v-model:value="formData.repeatDefectId" dict="tm_defect_manage,defect_title,id" placeholder="请选择重复缺陷" :disabled="disabled"  allowClear/>
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item :span="24" label="缺陷图片" v-bind="validateInfos.defectImg">
	          <j-image-upload  v-model:value="formData.defectImg" :disabled="disabled" :fileMax="5"></j-image-upload>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item :span="24" label="备注" v-bind="validateInfos.commets">
	          <a-textarea v-model:value="formData.commets" :rows="4" placeholder="请输入备注" :disabled="disabled" style="height:55px"  allowClear/>
          </a-form-item>
        </a-col>
     
      </a-row>
    </a-form>
  </a-spin>
</a-col>
    <a-col :xl="recordXl"  style="margin-bottom: 10px;width:500px" v-if="showFlag">
      <div style="margin-left: 10px;">
      <timeline>
    <timeline-item v-for="(rec, index) in records" :key="index">
      {{ rec.record }}
      <div style="margin-left:20px;" v-if="rec.comment">
         备注：{{ rec.comment }}
      </div>
      <div style="margin-left:20px;color=pink" v-if="rec.reason">
         处理意见：{{ rec.reason }}
      </div>
    </timeline-item>
  </timeline>
  </div>
    </a-col>
  </a-row> 
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onBeforeMount,onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  // import JSelectUser from '/@/components/Form/src/jeecg/components/JSelectUser.vue';
  import JTreeSelect from '/@/components/Form/src/jeecg/components/JTreeSelect.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate,projectSystemList } from '../DefectManage.api';
  import { Form } from 'ant-design-vue';
  
  import { Timeline, TimelineItem } from 'ant-design-vue';
  const refSystem = ref();
  const refSolverer = ref();
  
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    // formAddDisabled: { type: Boolean, default: false },
    // shown: { type: Boolean, default: false },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true },
    continueFlag: { type: Boolean, default: true },
    defectRecords: { type: Object, default: ()=>{} }
  });
  const defectXl = ref<number>(24);
  const recordXl = ref<number>(0);
  const projectId = ref<string>("");
  const searchProjectSystemString = ref<string>("");
  const searchSolvererString = ref<string>("");
  const shown = ref<boolean>(false);
  const showFlag = ref<boolean>(false);
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    defectId: '',  
    projectId: '',   
    batchId: '',   
    systemId: '',   
    systemModuleId: '',   
    functionName: '',   
    defectLevel: '',   
    defectType: '',   
    defectTitle: '',   
    description: '',   
    testStage: '',   
    envType: '',   
    defectPriority: '',   
    bugStatus: '1',   
    solverId: '',   
    isInfects: '',   
    infects: '',   
    noSloveReason: '',   
    defectReason: '',   
    defectReasonCata: '',
    defectImg: '',    
    repeatDefectId: '',   
    commets: '',   
  });
  const { createMessage } = useMessage();
  // const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  // const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const labelCol = ref<any>({style: { width: '100px' }})
  const wrapperCol = ref<any>({});
  const confirmLoading = ref<boolean>(false);
  // const showFlag = ref<boolean>(false);
  //表单验证
  let validatorRules = ref({
    projectId: [{ required: true, message: '请输入项目名称!'},],
    batchId: [{ required: true, message: '请输入批次名称!'},],
    systemId: [{ required: true, message: '请输入系统名称!'},],
    functionName: [{ required: true, message: '请输入功能点!'},],
    defectLevel: [{ required: true, message: '请输入缺陷等级!'},],
    defectType: [{ required: true, message: '请输入缺陷类型!'},],
    defectTitle: [{ required: true, message: '请输入缺陷描述!'},],
    description: [{ required: true, message: '请输入操作步骤!'},],
    testStage: [{ required: true, message: '请输入轮次名称!'},],
    envType: [{ required: true, message: '请输入环境!'},],
    defectPriority: [{ required: true, message: '请输入缺陷优先级!'},],
    bugStatus: [{ required: true, message: '请输入缺陷状态!'},],
    solverId: [{ required: true, message: '请输入缺陷处理人!'},],
    isInfects: [{ required: true, message: '请输入是否有影响!'},],
    infects: [{ required: true, message: '请输入影响范围!'},],
    noSloveReason: [{ required: true, message: '请输入不解决原因!'},],
    defectReason: [{ required: true, message: '请输入缺陷原因!'},],
    defectReasonCata: [{ required: true, message: '请输入原因分类!'},],
    repeatDefectId: [{ required: false, message: '请选择重复缺陷!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  // const showFlag = computed(()=>{
  //   console.log('####records:' + props.showFlag)
  //   return false;
  // });
  const records = computed(()=>{
    console.log('####records:' + props.defectRecords)
    return props.defectRecords;
  });
  /**
   * 是否有影响
   */
  function isInfectsChange(item) {
    console.log('####isInfectsChange:' + item)
    if(item=='0') {
      formData.infects = '无'
    } else {
      formData.infects = ''
    }
  }
  /**
   * 缺陷状态变更
   */
  const bugStatusCode = [5, 7, 8, 9, 12]
  function bugStatusChange(item) {
    console.log('####bugStatusChange:' + item);
    if (bugStatusCode.includes(Number(item))) {
      // shown.value = true
      validatorRules.value.noSloveReason[0].required = true;
    } else {
      // shown.value = false
      validatorRules.value.noSloveReason[0].required = false;
    }

    //无效缺陷
    if (Number(item) == 9) {
      // shown.value = true
      validatorRules.value.defectReason[0].required = true;
    }  else {
      validatorRules.value.defectReason[0].required = false;
    }
    //重复缺陷
    if (Number(item) == 10) {
      // shown.value = true
      validatorRules.value.repeatDefectId[0].required = true;
    } else {
      validatorRules.value.repeatDefectId[0].required = false;
    }
  }

  onMounted( async () => {
    showFlag.value = false
    // console.log('onMounted:' + formData.projectId)
    //   projectSystemList(record.projectId).then((resShow) => {
    //   console.log('edit projectSystemList' + JSON.stringify(resShow))
    // });
  })
  /**
   * 事件：选择项目
   */
  function projectChange(item) {
    formData.projectId=item
    searchProjectSystemString.value = "tm_project_system where project_id='"+item+"',system_name,id"
    refSystem.value.initSelectValue();
    searchSolvererString.value = "tm_project_user where project_id='"+item+"',realname,user_id"
    refSolverer.value.initSelectValue();
    formData.systemId=''

    // refSystem.value.loading()
  }
  /**
   * 新增
   */
  function continueAdd(record) {
    edit(record);
  }

  function add() {
    nextTick(() => {
      defectXl.value=24;
      recordXl.value=0;
      showFlag.value = false;
      resetFields();
      const tmpData = {};
      //赋值
      Object.assign(formData, tmpData);
    });
  }
  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      showFlag.value = true;
      defectXl.value=16;
      recordXl.value=8;
      searchProjectSystemString.value = "tm_project_system where project_id='"+record.projectId+"',system_name,id"
      refSystem.value.initSelectValue();
      searchSolvererString.value = "tm_project_user where project_id='"+record.projectId+"',realname,user_id"
      refSolverer.value.initSelectValue();
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  async function continueSubmitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          // emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }
  /**
   * 值改变事件触发
   * @param key
   * @param value
   */
  function handleFormChange(key, value) {
    formData[key] = value;
  }
  defineExpose({
    add,
    continueAdd,
    edit,
    submitForm,
    continueSubmitForm,
    formData,
    records,
    validatorRules,
    shown
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    height: 800px !important;
    overflow-y: auto;
    padding: 14px;
  }
</style>
